import request from "./request";
import axios from "axios";
import { encodeFilename } from "@/utils/file";

export function fetchLogin<T = any>(params: {
  password?: string;
  pass64?: string;
  username: string;
  remember: boolean;
}) {
  const resPara = {
    ...params,
  };
  if (resPara.pass64) resPara.pass64 = btoa(resPara.pass64);
  return request<T>({
    url: `/supgpt-app/chat-tool-app/system-manager/umsAdmin/login`,
    method: "POST",
    data: {
      data: resPara,
    },
  });
}

export function resetSelfPwd<T = any>(params: {
  confirmPwd: string;
  newPwd: string;
}) {
  return request<T>({
    url: `/supgpt-app/chat-tool-app/system-manager/umsAdmin/resetSelfPwd`,
    method: "POST",
    data: {
      data: params,
    },
  });
}

export function getWxCode<T = any>(params: { saasId: string }) {
  return request<T>({
    url: `/mt-middleware-server/weapp-official-accounts/qrcode/create/supTPT`,
    method: "POST",
    data: {
      expire_seconds: 30 * 60,
      action_name: "QR_STR_SCENE",
      action_info: {
        scene: {
          scene_str: `supTPT_mini$${params.saasId}`,
        },
      },
    },
  });
}

export async function getMenuList<T = any>() {
  return request<T>({
    url: "/supgpt-app/chat-tool-app/system-manager/umsMenu/treeList",
    method: "POST",
  });
}

export async function getAuthList<T = any>() {
  return request<T>({
    url: "/supgpt-app/chat-tool-app/license/list",
    method: "GET",
    fetchOptions: {
      filterExpired: true,
    },
  });
}

export async function fetchRefreshToken<T = any>() {
  const refreshToken = localStorage.getItem("refreshToken");
  const orgCode = localStorage.getItem("orgCode");
  if (refreshToken && orgCode) {
    const fromData = new FormData();
    fromData.append("refreshToken", refreshToken.replace(/^"|"$/g, ""));
    fromData.append("orgCode", orgCode);
    const headers: any = {};
    // const token = localStorage.getItem('token')
    // if (token) {
    //     headers['Authorization'] = `Bearer ${token.replace(/^"|"$/g, '')}`
    // }
    const url =
      "/supgpt-app/chat-tool-app/system-manager/umsAdmin/refreshToken";
    const reRes: any = await axios({
      url,
      method: "POST",
      headers,
      data: fromData,
    });
    if (reRes.data && reRes.data.isSuccess) {
      localStorage.setItem("refreshToken", reRes.data.content.refreshToken);
      localStorage.setItem("token", reRes.data.content.token);
      localStorage.setItem("tokenHead", reRes.data.content.tokenHead);
      localStorage.setItem("tokenHeader", reRes.data.content.tokenHeader);
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

let intervalTimer: NodeJS.Timer | null = null;

export async function intervalRefreshToken<T = any>() {
  if (intervalTimer) clearInterval(intervalTimer);
  intervalTimer = setInterval(async () => {
    await fetchRefreshToken();
  }, 1000 * 60 * 60);
}

export function fetchUserInfo<T = any>() {
  return request<T>({
    url: `/supgpt-app/chat-tool-app/system-manager/umsAdmin/info`,
    method: "GET",
  });
}

export function getMicroApps(url: string) {
  return request({
    url: `${url}/lib.json?id=${Math.floor(Math.random() * 10000 + 1)}`,
    method: "GET",
  });
}

export function getFile(url: string) {
  const resUrl = encodeFilename(url);
  return request({
    url: `/supgpt-app/chat-tool-app/system-file/sup-file${resUrl}`,
    method: "GET",
    responseType: "blob",
  });
}

// dev use
export function delAppProject<T = any>(params: { code: string }) {
  return request<T>({
    url: `/supgpt-app/app-download/api/projectDelete`,
    method: "POST",
    data: params,
  });
}
